package com.googlecode.jvmpart.test;

import java.io.File;
import java.net.URL;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.googlecode.jvmpart.proc.JvmProcessException;
import com.googlecode.jvmpart.proc.regex.URLContentProcessor;
import com.googlecode.jvmpart.utils.URLUtils;

public class Flash8Processor extends URLContentProcessor {

	@Override
	public boolean matchProcess(Matcher m, int offset) throws JvmProcessException {
		int i = 1;i++;
		String imgurl = m.group(i++);
//		String name = m.group(i++);
		if (!imgurl.startsWith("http")) return false;
		try {
			URL url = new URL(imgurl);
//			String path = url.getPath();
//			int ind = path.lastIndexOf("/");
//			path = path.substring(0, ind);
			String title = getTitle();
			title = title.substring(0, title.lastIndexOf(" "));
			String[] names = getTitle().split("\\s\\-\\s");
			String[] groups = names[2].split(" ");
			String group = null;
			if(groups!=null&&groups.length>0) {
				group = groups[0];
			} else {
				group = names[2];
			}
//			System.out.println(url);
			File dir = new File("e:\\flash8"+File.separator+group+File.separator+names[1]);
			if(!dir.exists()) dir.mkdirs();
			URLUtils.simpleDownload(url, dir);
		} catch (Throwable e) {
			throw new JvmProcessException("download error", e);
		}		
		return false;
	}

	@Override
	public Pattern regexPattern(Map<String, String> params) {
		return Pattern.compile("<a\\s+[^>]*href=(['|\"]*)([^\\s]+\\.mp3)\\1[^>]*>",
				Pattern.CASE_INSENSITIVE);
	}

}
